<?php

namespace SDXApi\Model;

use Think\Model;
class ShippingModel extends Model {
	/**
	 *
	 * @return $data 系统配送方式
	 */
	public function get_shipping_list() {
		$map = array ();
		$map['enabled'] = 1;
		$res = $this->field ( 'shipping_id,shipping_code,shipping_name,shipping_desc' )->where ( $map )->order('shipping_order')->select ();
		$data = array ();
		if ($res) {
			$data ['list'] = $res;
		}
		return $data;
	}
	
	
	/**
	 * 取得某配送方式对应于某收货地址的区域信息
	 * @param   int     $shipping_id        配送方式id
	 * @param   array   $region_id_list     收货人地区id数组
	 * @return  array   配送区域信息（config 对应着反序列化的 configure）
	 */
	public function shipping_area_info($shipping_id, $region_id_list) {
	    $sql = 'SELECT s.shipping_code, s.shipping_name, ' .
	        's.shipping_desc, s.insure, s.support_cod, a.configure ' .
	        'FROM ' . C('DB_PREFIX') . 'shipping AS s, ' .
	        C('DB_PREFIX') . 'shipping_area AS a, ' .
	        C('DB_PREFIX') . 'area_region AS r ' .
	        "WHERE s.shipping_id = '$shipping_id' " .
	        'AND r.region_id ' . db_create_in($region_id_list) .
	        ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 limit 1';
	    $Model=new Model();
	    $row = $Model->query($sql);
	    $row =$row[0];
	    if (!empty($row)) {
	        $shipping_config = unserialize_config($row['configure']);
	        if (isset($shipping_config['pay_fee'])) {
	            if (strpos($shipping_config['pay_fee'], '%') !== false) {
	                $row['pay_fee'] = floatval($shipping_config['pay_fee']) . '%';
	            } else {
	                $row['pay_fee'] = floatval($shipping_config['pay_fee']);
	            }
	        } else {
	            $row['pay_fee'] = 0.00;
	        }
	    }
	
	    return $row;
	}
	
	
	/**
	 * 取得可用的配送方式列表
	 * @param   array   $region_id_list     收货人地区id数组（包括国家、省、市、区）
	 * @return  array   配送方式数组
	 */
	public function available_shipping_list($region_id_list) {
	    $sql = 'SELECT s.shipping_id, s.shipping_code, s.shipping_name, ' .
	        's.shipping_desc, s.insure, s.support_cod, a.configure ' .
	        'FROM ' . C('DB_PREFIX') . 'shipping AS s, ' .
	        C('DB_PREFIX') . 'shipping_area AS a, ' .
	        C('DB_PREFIX') . 'area_region AS r ' .
	        'WHERE r.region_id ' . db_create_in($region_id_list) .
	        ' AND r.shipping_area_id = a.shipping_area_id AND a.shipping_id = s.shipping_id AND s.enabled = 1 ORDER BY s.shipping_order';
	    $Model=new Model();
	    return $Model->query($sql);
	}
	
	/**
	 * 取得配送方式信息
	 * @param   int     $shipping_id    配送方式id
	 * @return  array   配送方式信息
	 */
	public function shipping_info($shipping_id) {
	    $sql = 'SELECT * FROM ' . C('DB_PREFIX') .
	    "shipping WHERE shipping_id = '$shipping_id' " .
	    'AND enabled = 1 limit 1';
	    $Model=new Model();
	    $row=$Model->query($sql);
	    return $row[0];
	}
}
?>